package com.example.smartg.ui.dashboard;

import android.content.Intent;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import androidx.navigation.NavController;
import androidx.navigation.Navigation;
import okhttp3.Call;
import okhttp3.Response;

import com.example.smartg.HttpUtil;
import com.example.smartg.ManagerLoginActivity;
import com.example.smartg.R;
import com.example.smartg.SmartGMainActivity;
import com.example.smartg.SpUtils;
import com.example.smartg.utils.ToastUtil;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;

public class DashboardFragment extends Fragment {

    public View view;
    public Button send_code_btn;
    private TimeCount time;
    public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        if(view == null) {
            view = inflater.inflate( R.layout.fragment_dashboard, container,false);
        }
        ImageView imageView = (ImageView) view.findViewById(R.id.return_to_home);
        imageView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(getActivity(), SmartGMainActivity.class);
                startActivity(intent);
            }
        });
        send_code_btn = (Button) view.findViewById(R.id.send_code);
        time = new TimeCount(60000, 1000);
        send_code_btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                EditText editTextPhone = (EditText)view.findViewById(R.id.phone_num) ;
                to_send_code(editTextPhone.getText().toString());
            }
        });
        Button login_btn = (Button) view.findViewById(R.id.to_login);
        login_btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                  EditText editTextPhone = (EditText) view.findViewById(R.id.phone_num);
                  EditText editTextCode= (EditText) view.findViewById(R.id.verification_code);
                  phone_login(editTextPhone.getText().toString(),editTextCode.getText().toString());
            }
        });
        ImageView cls_phonenum = (ImageView) view.findViewById(R.id.clear_phonenum);
        cls_phonenum.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                EditText editTextPhone = (EditText) view.findViewById(R.id.phone_num);
                editTextPhone.setText("");
            }
        });
        return view;

    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
    }

    public void phone_login(String phone_num,String verification_code) {
        String url = "http://10.2.47.115/smartg_api/login_manage/login_in_by_verification_code";
        //实例化
        HttpUtil httpUtil = new HttpUtil();
        JSONObject json = new JSONObject();
        try {
            json.put("phone_num", phone_num);
            json.put("verification_code", verification_code);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        httpUtil.sendOkHttpRequest(url, json.toString(), new okhttp3.Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                getActivity().runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        ToastUtil.error(getActivity(),"服务器出错！");
                    }
                });
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                String responsedata = response.body().string();
                Log.e("responsedata",responsedata);
                JSONObject jsonObject = null;
                try {
                    jsonObject = new JSONObject(responsedata);
                    String msg = jsonObject.optString("msg");
                    int code = jsonObject.optInt("code");
                    if (code == 20000) {
                        JSONObject data = jsonObject.optJSONObject("data");
                        String token = data.optString("token");
                        String user_name = data.optString("name");
                        // 记住用户信息到SharedPreferences
                        SpUtils.putString(getActivity(),"token",token);
                        SpUtils.putString(getActivity(),"user_name",user_name);

                        // 跳转到管理员界面？还是跳转到上一界面?
                        getActivity().finish();
                    } else {
                        getActivity().runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                Log.e("msg",msg);
                                ToastUtil.error(getActivity(),msg);
                            }
                        });
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        });
    }
    public void to_send_code(String phone_num) {
        String url = "http://10.2.47.115/smartg_api/login_manage/get_verification_code";
        //实例化
        HttpUtil httpUtil = new HttpUtil();
        JSONObject json = new JSONObject();
        try {
            json.put("phone_num", phone_num);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        httpUtil.sendOkHttpRequest(url, json.toString(), new okhttp3.Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                getActivity().runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        ToastUtil.error(getActivity(),"服务器出错！");
                    }
                });
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                String responsedata = response.body().string();
                Log.e("responsedata",responsedata);
                JSONObject jsonObject = null;
                try {
                    jsonObject = new JSONObject(responsedata);
                    String msg = jsonObject.optString("msg");
                    int code = jsonObject.optInt("code");
                    if (code == 20000) {
                        //倒数60秒
                        getActivity().runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                // 启动计时
                                time.start();
                            }
                        });
                    } else {
                        getActivity().runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                Log.e("msg",msg);
                                ToastUtil.error(getActivity(),msg);
                            }
                        });
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        });
    }
    class TimeCount extends CountDownTimer {

        public TimeCount(long millisInFuture, long countDownInterval) {
            super(millisInFuture, countDownInterval);
        }

        @Override
        public void onTick(long millisUntilFinished) {
            send_code_btn.setClickable(false);
            send_code_btn.setText("("+millisUntilFinished / 1000 +") ");
        }

        @Override
        public void onFinish() {
            send_code_btn.setText("发送验证码");
            send_code_btn.setClickable(true);

        }
    }

}